package learninglucene;

import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.LockObtainFailedException;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.Version;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.*;

/**
 * A very simple example where Lucene is used to index all the files in a directory
 * and then a search is made for a string.
 * @author Ankit Gupta
 */
public class SimpleLucene {
    
    private static String str_sampleTextDir = "data";
    private static Directory directory;
    
    public static void main(String[] args) {
        createIndex();
        String searchString = null;
        if (args.length == 0) {
            searchString = "India";
        }else{
            searchString = args[0];
        }
        System.out.println(args.length);
        searchIndex(searchString);
    }
    
    /**
     * Creates an index for the files in the data directory.
     */
    private static void createIndex() {
        try {
            File documentDir = new File(str_sampleTextDir);
            if (!documentDir.exists()) {
                System.err.println("The document " + str_sampleTextDir + " does not exist!");
                System.exit(1);
            }
            
            Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_30);
            directory = new RAMDirectory();
            IndexWriter indexWriter = null;
            try {
                indexWriter = new IndexWriter(directory, analyzer, IndexWriter.MaxFieldLength.UNLIMITED);
                
            } catch (CorruptIndexException ex) {
                Logger.getLogger(SimpleLucene.class.getName()).log(Level.SEVERE, null, ex);
            } catch (LockObtainFailedException ex) {
                Logger.getLogger(SimpleLucene.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(SimpleLucene.class.getName()).log(Level.SEVERE, null, ex);
            }
            
            File[] documents = documentDir.listFiles();
            for (File f : documents) {
                Reader reader = null;
                try {
                    Document document = new Document();
                    reader = new FileReader(f);
                    document.add(new Field("path", f.getCanonicalPath(), Field.Store.YES, Field.Index.NOT_ANALYZED));
                    document.add(new Field("contents", reader));
                    indexWriter.addDocument(document);
                } catch (FileNotFoundException ex) {
                    Logger.getLogger(SimpleLucene.class.getName()).log(Level.SEVERE, null, ex);
                } finally {
                    try {
                        reader.close();
                    } catch (IOException ex) {
                        Logger.getLogger(SimpleLucene.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
            
            indexWriter.close();
        } catch (CorruptIndexException ex) {
            Logger.getLogger(SimpleLucene.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(SimpleLucene.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    
    /**
     * searches for a string in the index
     * @param searchString the string to be searched.
     */
    private static void searchIndex(String searchString) {
        try {
            System.out.println("Searching for '" + searchString + "'");
            Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_30);
            QueryParser queryParser = new QueryParser(Version.LUCENE_30, "contents", analyzer);
            Query query = queryParser.parse(searchString);
            
            //find top 10 documents containing searchString
            TopScoreDocCollector resultCollector = TopScoreDocCollector.create(10, true);
            
            
            IndexReader indexReader = IndexReader.open(directory);
            IndexSearcher indexSearcher = new IndexSearcher(indexReader);
            indexSearcher.search(query, resultCollector);
            
            ScoreDoc[] hits = resultCollector.topDocs().scoreDocs;
            
            int i = 0;
            for (ScoreDoc doc : hits) {
                int docId = doc.doc;
                Document d = indexSearcher.doc(docId);
                System.out.println((++i) + ". " + d.get("path"));
            }
        } catch (ParseException ex) {
            Logger.getLogger(SimpleLucene.class.getName()).log(Level.SEVERE, null, ex);
        } catch (CorruptIndexException ex) {
            Logger.getLogger(SimpleLucene.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(SimpleLucene.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
